package com.hhh.springai_test.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhh.springai_test.common.BaseResponse;
import com.hhh.springai_test.common.ErrorCode;
import com.hhh.springai_test.common.ResultUtils;
import com.hhh.springai_test.constant.UserConstant;
import com.hhh.springai_test.exception.BusinessException;
import com.hhh.springai_test.model.dto.bookborrow.BookBorrowAddRequest;
import com.hhh.springai_test.model.dto.bookborrow.BookBorrowQueryRequest;
import com.hhh.springai_test.model.dto.bookborrow.BookBorrowUpdateRequest;
import com.hhh.springai_test.model.po.BookBorrow;
import com.hhh.springai_test.model.vo.BookBorrowVO;
import com.hhh.springai_test.service.BookBorrowService;
import cn.dev33.satoken.annotation.SaCheckRole;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/bookBorrow")
public class BookBorrowController {

    @Resource
    private BookBorrowService bookBorrowService;

    @PostMapping("/add")
    @SaCheckRole(UserConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> addBookBorrow(@RequestBody List<BookBorrowAddRequest> bookBorrowAddRequests) {
        Long userId = StpUtil.getLoginIdAsLong();
        boolean result = bookBorrowService.addBookBorrows(bookBorrowAddRequests,userId);
        return ResultUtils.success(result);
    }

    @PostMapping("/update")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateBookBorrow(@RequestBody BookBorrowUpdateRequest updateRequest) {
        Long userId = StpUtil.getLoginIdAsLong();
        boolean result = bookBorrowService.updateBookBorrow(updateRequest,userId);
        return ResultUtils.success(result);
    }

    @PostMapping("/delete/{id}")
    @SaCheckRole(UserConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> deleteBookBorrow(@PathVariable Long id) {
        BookBorrow byId = bookBorrowService.getById(id);
        if (byId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "借阅记录不存在");
        }
        boolean result = bookBorrowService.removeById(id);
        return ResultUtils.success(result);
    }

    @PostMapping("/list")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<BookBorrowVO>> listBookBorrow(@RequestBody BookBorrowQueryRequest queryRequest) {
        Page<BookBorrowVO> page = bookBorrowService.listBookBorrowByPage(queryRequest);
        return ResultUtils.success(page);
    }

    @PostMapping("/my/list")
    @SaCheckRole(UserConstant.DEFAULT_ROLE)
    public BaseResponse<Page<BookBorrowVO>> listMyBookBorrows(@RequestBody BookBorrowQueryRequest queryRequest) {
        Long userId = StpUtil.getLoginIdAsLong();
        Page<BookBorrowVO> page = bookBorrowService.listUserBookBorrows(queryRequest, userId);
        return ResultUtils.success(page);
    }
}
